import os
import threading
import time
import tkinter as tk
from tkinter import filedialog, messagebox

import ttkbootstrap as ttk
from PIL import Image
from ttkbootstrap.constants import *

from app.util.annotation_util import annotate, ClassInfo
from app.view.base_view import View


@annotate(ClassInfo(name="ImgConvertor", category="tool"))
class ImgConvertorView(View):
    """设置视图"""

    def __init__(self, parent, controller):
        super().__init__(parent, controller)
        # 初始化数据库
        # 设置中文字体支持
        self.style = ttk.Style()
        self.style.configure(".", font=("SimHei", 10))

        # 存储待转换的文件列表
        self.file_list = []
        self.output_dir = os.path.join(os.path.expanduser("~"), "Desktop\\img")

        # 创建输出目录
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

        # 创建UI组件
        self._create_widgets()

    def _create_widgets(self):
        """创建界面组件"""
        # 顶部控制区域
        top_frame = ttk.LabelFrame(self, text="转换设置", padding=10)
        top_frame.pack(fill=X, padx=10, pady=5)

        # 源文件选择
        file_frame = ttk.Frame(top_frame)
        file_frame.pack(fill=X, pady=5)

        ttk.Button(
            file_frame,
            text="添加图片",
            command=self.add_files,
            bootstyle=SUCCESS
        ).pack(side=LEFT, padx=5)

        ttk.Button(
            file_frame,
            text="移除选中",
            command=self.remove_selected,
            bootstyle=WARNING
        ).pack(side=LEFT, padx=5)

        ttk.Button(
            file_frame,
            text="清空列表",
            command=self.clear_list,
            bootstyle=DANGER
        ).pack(side=LEFT, padx=5)

        # 输出格式选择
        format_frame = ttk.Frame(top_frame)
        format_frame.pack(fill=X, pady=5)

        ttk.Label(format_frame, text="目标格式:").pack(side=LEFT, padx=5)

        self.target_format = tk.StringVar(value="png")
        format_options = ttk.Combobox(
            format_frame,
            textvariable=self.target_format,
            values=["png", "jpg", "jpeg", "bmp", "gif"],
            state="readonly",
            width=10
        )
        format_options.pack(side=LEFT, padx=5)

        # JPG质量设置
        self.quality_var = tk.IntVar(value=95)
        quality_frame = ttk.Frame(top_frame)
        quality_frame.pack(fill=X, pady=5)

        ttk.Label(quality_frame, text="图片质量 (1-100):").pack(side=LEFT, padx=5)
        quality_scale = ttk.Scale(
            quality_frame,
            from_=1,
            to=100,
            variable=self.quality_var,
            orient=HORIZONTAL,
            length=200
        )
        quality_scale.pack(side=LEFT, padx=5)

        self.quality_label = ttk.Label(quality_frame, text=str(self.quality_var.get()))
        self.quality_label.pack(side=LEFT, padx=5)
        self.quality_var.trace_add("write", self.update_quality_label)

        # 输出目录设置
        dir_frame = ttk.Frame(top_frame)
        dir_frame.pack(fill=X, pady=5)

        ttk.Label(dir_frame, text="输出目录:").pack(side=LEFT, padx=5)

        self.dir_entry = ttk.Entry(dir_frame)
        self.dir_entry.pack(side=LEFT, fill=X, expand=True, padx=5)
        self.dir_entry.insert(0, self.output_dir)

        ttk.Button(
            dir_frame,
            text="浏览...",
            command=self.choose_output_dir,
            bootstyle=INFO
        ).pack(side=LEFT, padx=5)

        # 转换按钮
        ttk.Button(
            top_frame,
            text="开始转换",
            command=self.start_conversion,
            bootstyle=PRIMARY,
            width=20
        ).pack(pady=10)

        # 中间文件列表区域
        list_frame = ttk.LabelFrame(self, text="待转换文件", padding=10)
        list_frame.pack(fill=BOTH, expand=True, padx=10, pady=5)

        self.file_listbox = tk.Listbox(
            list_frame,
            # bootstyle=INFO,
            selectmode=tk.EXTENDED
        )
        self.file_listbox.pack(fill=BOTH, expand=True)

        # 底部状态区域
        status_frame = ttk.LabelFrame(self, text="转换状态", padding=10)
        status_frame.pack(fill=BOTH, expand=True, padx=10, pady=5)

        self.status_text = ttk.Text(
            status_frame,
            height=5,
            state=DISABLED,
            wrap=tk.WORD
        )
        self.status_text.pack(fill=BOTH, expand=True)

        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            status_frame,
            variable=self.progress_var,
            maximum=100,
            bootstyle=SUCCESS
        )
        self.progress_bar.pack(fill=X, pady=5)

    def update_quality_label(self, *args):
        """更新质量标签显示"""
        self.quality_label.config(text=str(self.quality_var.get()))

    def add_files(self):
        """添加图片文件"""
        file_types = [
            ("图片文件", "*.png;*.jpg;*.jpeg;*.bmp;*.gif"),
            ("所有文件", "*.*")
        ]
        files = filedialog.askopenfilenames(filetypes=file_types)

        if files:
            added_count = 0
            for file in files:
                if file not in self.file_list:
                    self.file_list.append(file)
                    self.file_listbox.insert(tk.END, os.path.basename(file))
                    added_count += 1
            self.log(f"已添加 {added_count} 个文件")

    def remove_selected(self):
        """移除选中的文件"""
        selected_indices = self.file_listbox.curselection()
        if selected_indices:
            # 从后往前删除，避免索引问题
            for i in sorted(selected_indices, reverse=True):
                del self.file_list[i]
                self.file_listbox.delete(i)
            self.log(f"已移除 {len(selected_indices)} 个文件")

    def clear_list(self):
        """清空文件列表"""
        if self.file_list:
            self.file_list.clear()
            self.file_listbox.delete(0, tk.END)
            self.log("已清空文件列表")

    def choose_output_dir(self):
        """选择输出目录"""
        dir_path = filedialog.askdirectory()
        if dir_path:
            self.output_dir = dir_path
            self.dir_entry.delete(0, tk.END)
            self.dir_entry.insert(0, dir_path)
            self.log(f"输出目录已设置为: {dir_path}")

    def log(self, message):
        """记录状态信息"""
        timestamp = time.strftime("%H:%M:%S")
        self.status_text.config(state=tk.NORMAL)
        self.status_text.insert(tk.END, f"[{timestamp}] {message}\n")
        self.status_text.see(tk.END)
        self.status_text.config(state=tk.DISABLED)

    def start_conversion(self):
        """开始转换图片格式"""
        if not self.file_list:
            messagebox.showwarning("警告", "请先添加图片文件")
            return

        target_format = self.target_format.get().lower()
        output_dir = self.dir_entry.get()

        if not os.path.exists(output_dir):
            try:
                os.makedirs(output_dir)
                self.log(f"创建输出目录: {output_dir}")
            except Exception as e:
                messagebox.showerror("错误", f"无法创建输出目录: {str(e)}")
                return

        # 禁用转换按钮防止重复点击
        self.log(f"开始转换，目标格式: {target_format}")
        self.progress_var.set(0)

        # 在新线程中执行转换，避免UI冻结
        threading.Thread(
            target=self.convert_images,
            args=(target_format, output_dir),
            daemon=True
        ).start()

    def convert_images(self, target_format, output_dir):
        """转换图片格式的核心函数"""
        total_files = len(self.file_list)
        success_count = 0
        error_count = 0

        for i, file_path in enumerate(self.file_list):
            try:
                # 更新进度
                progress = (i / total_files) * 100
                self.progress_var.set(progress)

                # 获取文件名和扩展名
                file_name = os.path.basename(file_path)
                name_without_ext = os.path.splitext(file_name)[0]

                # 构建输出路径
                output_path = os.path.join(
                    output_dir,
                    f"{name_without_ext}.{target_format}"
                )

                # 打开图片并转换格式
                with Image.open(file_path) as img:
                    # 处理透明通道（如果有）
                    if target_format in ['jpg', 'jpeg'] and img.mode in ('RGBA', 'LA'):
                        background = Image.new(img.mode[:-1], img.size, (255, 255, 255))
                        background.paste(img, img.split()[-1])
                        img = background
                    elif img.mode == 'P':
                        img = img.convert('RGB')

                    # 保存图片
                    save_params = {}
                    if target_format in ['jpg', 'jpeg']:
                        save_params['quality'] = self.quality_var.get()
                        save_params['optimize'] = True

                    img.save(output_path, target_format.upper(), **save_params)

                success_count += 1
                self.log(f"转换成功: {file_name}")

            except Exception as e:
                error_count += 1
                self.log(f"转换失败 {file_name}: {str(e)}")

            # 短暂延迟，确保UI有时间更新
            time.sleep(0.01)

        # 完成转换
        self.progress_var.set(100)
        self.log(f"转换完成 - 成功: {success_count}, 失败: {error_count}")
        messagebox.showinfo(
            "转换完成",
            f"转换完成\n成功: {success_count} 个文件\n失败: {error_count} 个文件\n输出目录: {output_dir}"
        )

    def create_widgets(self):
        pass
